/**
 * 
 */
package com.lanswon.qzsmk.service.cardManageService.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ch.qos.logback.classic.Logger;

import com.lanswon.common.card.CardUtil;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.ApplyBatchRecordMapper;
import com.lanswon.qzsmk.dao.BatchCollectionMapper;
import com.lanswon.qzsmk.dao.BlackListGenMapper;
import com.lanswon.qzsmk.dao.BlackListRcMapper;
import com.lanswon.qzsmk.dao.BusiParamMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardBatchMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardNoGeneratedMapper;
import com.lanswon.qzsmk.dao.CardPhysicsTypeMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardTaskMapper;
import com.lanswon.qzsmk.dao.CardTypeMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CertificateMapper;
import com.lanswon.qzsmk.dao.CooperationCompanyMapper;
import com.lanswon.qzsmk.dao.CorporationMapper;
import com.lanswon.qzsmk.dao.PersonalMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.ApplyBatchRecord;
import com.lanswon.qzsmk.model.BatchCollection;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardBatch;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.CardNoGenerated;
import com.lanswon.qzsmk.model.CardPhysicsType;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.CardTask;
import com.lanswon.qzsmk.model.CardType;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.CooperationCompany;
import com.lanswon.qzsmk.model.Personal;
import com.lanswon.qzsmk.service.cardManageService.ApplyCardService;
import com.lanswon.qzsmk.service.cardManageService.MakeCardService;
import com.lanswon.qzsmk.util.CitizenCardNoGeneratorUtil;
import com.lanswon.qzsmk.util.CommonUtil;
import com.lanswon.qzsmk.util.FileUtil;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.util.ZipUtil;
import com.lanswon.qzsmk.vo.BankProvidePersonalVo;
import com.lanswon.qzsmk.vo.CardNoGeneratedVo;
import com.lanswon.qzsmk.vo.ImportBankFileVo;
import com.lanswon.qzsmk.vo.MakeCardFileReturnFileVo;
import com.lanswon.qzsmk.vo.MakeCardInfo;
import com.lanswon.qzsmk.vo.MakeCardInfo2;
import com.lanswon.qzsmk.vo.MakeCardParamVo;
import com.lanswon.qzsmk.vo.MakeCardQueryConditionVo;
import com.lanswon.qzsmk.vo.MakeCardQueryResultVo;
import com.lanswon.qzsmk.vo.PersonalVo;

/**
 * @author sun
 *
 */
@Service
@Transactional
public class MakeCardServiceImpl implements MakeCardService {
	
	private static Logger logger = (Logger) LoggerFactory.getLogger(MakeCardServiceImpl.class);
	

	@Autowired
	CertMapper cem;
	
	@Autowired
	BusiParamMapper bpm;
	
	@Autowired
	BusinessMapper bm;

	@Autowired
	BatchCollectionMapper bcm;

	@Autowired
	PersonalMapper pm;

	@Autowired
	CardBatchMapper cbm;

	@Autowired
	CardTaskMapper ctm;

	@Autowired
	CooperationCompanyMapper ccm;

	@Autowired
	CardProdunctDefinitionMapper cpdm;

	@Autowired
	CorporationMapper cm;

	@Autowired
	CardControlMapper cardm;

	@Autowired
	CardDataMapper cdm;

	@Autowired
	ApplyCardService acs;

	@Autowired
	CooperationCompanyMapper cocm;
	
	@Autowired
	CertificateMapper cfm;
	
	@Autowired
	CardPhysicsTypeMapper cptm;
	
	@Autowired
	CardManageMapper cmm;
	
	@Autowired
	AppOpenRegMapper aorm;
	
	@Autowired
	SubaccountPersonalMapper spm;
	
	@Autowired
	BlackListGenMapper blgm;
	
	@Autowired
	BlackListRcMapper blrm;

	@Autowired
	ApplyBatchRecordMapper abrm;
	
	@Autowired
	CardTypeMapper cardTypeMapper;
	
	@Autowired
	CardNoGeneratedMapper cardNoGeneratedMapper;

	@Override
	public DwzPage<PersonalVo> queryPersonalByCardTaskNo(
			MakeCardQueryConditionVo mcv) {
		List<Personal> list = pm.queryPersonalByCardTaskNo(mcv);
		List<PersonalVo> l = new ArrayList<>();
		for (Personal p : list) {
			PersonalVo pv = new PersonalVo();
			pv.setCustomerName(p.getCustomerName());
			pv.setGender(p.getGender());
			pv.setPaperNo(p.getPaperNo());
			pv.setPaperType(cfm.queryCertificateByCode(p.getPaperType()).getCertificatesName());
			pv.setCardTaskNo(mcv.getCardTaskNo());
			l.add(pv);
		}

		int totalCount = pm.queryPersonalCountByCardTaskNo(mcv.getCardTaskNo());
		DwzPage<PersonalVo> dp = new DwzPage<PersonalVo>(mcv.getCurrentPage(),
				mcv.getNumPerPage(), totalCount);
		dp.setList(l);
		return dp;
	}

	@Override
	public DwzPage<PersonalVo> queryPersonalByApplybatchNo(
			MakeCardQueryConditionVo mcv) {

		List<Personal> list = pm.queryPersonalByApplybatchNo(mcv);
		List<PersonalVo> l = new ArrayList<>();
		for (Personal p : list) {
			PersonalVo pv = new PersonalVo();
			pv.setCustomerName(p.getCustomerName());
			pv.setGender(p.getGender());
			pv.setPaperNo(p.getPaperNo());
			pv.setPaperType(cfm.queryCertificateByCode(p.getPaperType()).getCertificatesName());
			pv.setApplyBatchNo(p.getApplyBatchNo());
			l.add(pv);
		}
		int totalCount = pm.queryPersonalCountByApplyBatchNo(mcv.getApplyNo());
		DwzPage<PersonalVo> dp = new DwzPage<PersonalVo>(mcv.getCurrentPage(),
				mcv.getNumPerPage(), totalCount);
		dp.setList(l);
		return dp;
	}

	@Override
	public DwzPage<MakeCardQueryResultVo> queryBatchCollection(
			MakeCardQueryConditionVo mcv) {
		mcv.setClaimStatus(CardContants.CLAIM_STATUS_APPLY);
		List<BatchCollection> ll = bcm.queryBatchCollection(mcv);

		List<MakeCardQueryResultVo> list = new ArrayList<>();
		for (BatchCollection b : ll) {
			MakeCardQueryResultVo mqv = new MakeCardQueryResultVo();
			mqv.setApplyBatchNo(b.getApplyBatchNo());
			mqv.setCardPName(cpdm.queryCardPCode(b.getCardPCode())
					.getCardpName());
			mqv.setApplyNetDot(b.getCollBranchName());
			mqv.setNumber(b.getRecordNum());
			mqv.setApplyDate(b.getLastDate());
			mqv.setCorp(cm.queryCorporationByCode(b.getCorpCode())
					.getCorpName());
			mqv.setDesc(b.getIsUrgent());
			list.add(mqv);
		}
		int totalCount = bcm.queryBatchCollectionCount(mcv);
		DwzPage<MakeCardQueryResultVo> dp = new DwzPage<MakeCardQueryResultVo>(
				mcv.getCurrentPage(), mcv.getNumPerPage(), totalCount);
		dp.setList(list);
		return dp;
	}
	

	public void finishMakeCardTask(List<String>list,ImportBankFileVo vv){
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		Date now = new Date();
		for(String str:list){
			String [] info = StringUtils.splitPreserveAllTokens(str, "|");
			MakeCardFileReturnFileVo vo= new MakeCardFileReturnFileVo();
			vo.setFileName(info[0]);
			vo.setChipsLessNo(info[1]);
			vo.setChipsLessPin(info[2]);
			vo.setCitizenCardNo(info[3]);
			vo.setReturnDate(info[4]);
			vo.setCardSeqNo(info[5]);
			vo.setBcNo(info[6]);
			vo.setBcValidTime(info[7]);
			vo.setMakeCardResult(info[8]);
			vo.setMakeCardFailReason(info[9]);
			vo.setOriMakeCardData(info[10]);
			
			if(CardContants.MAKE_CARD_RESULT_SUCCESS.equals(vo.getMakeCardResult())){
			
				CardControl cc = cardm.queryCardControlByCitizenCardNo(vo.getCitizenCardNo());
			cc.setCardPosition(CardContants.CARD_POSITION_NET_DOT);
			
			try {
				cc.setCardDate(DateUtils.parseDate(vo.getReturnDate(), "yyyyMMdd"));
			} catch (ParseException e) {
				e.printStackTrace();
				String msg="日期格式化异常";
				logger.error(msg);
				throw new SystemException(SystemException.ParseException, msg);

			}
			cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
			
			cardm.updateCardControl(cc);
			
			CardData cd = cdm.queryCardDataByCitizenCardNo(vo.getCitizenCardNo());
			cd.setCardSeqNo(vo.getCardSeqNo());
			try {
				cd.setCardValidTime(DateUtils.parseDate(vo.getBcValidTime(), "yyyyMMdd"));
			} catch (ParseException e) {
				e.printStackTrace();
				String msg="日期格式化异常";
				logger.error(msg);
				throw new SystemException(SystemException.ParseException, msg);

			}
			cd.setChipsLessNo(vo.getChipsLessNo());
			cd.setChipsLessPin(vo.getChipsLessPin());
			cdm.update(cd);
			
			}else if(CardContants.MAKE_CARD_RESULT_FAIL.equals(vo.getMakeCardResult())){
				logger.info("制卡失败,卡面号[{}]",vo.getCitizenCardNo());
			}
			
			CardTask ct = ctm.queryCardTaskByCardTaskNo(vv.getFileName().replace("R", "Q"));
			ct.setTaskStatus(CardContants.ALREADY_MADE_CARD);
			ctm.updateCardTask(ct);
			
			CardBatch cb = cbm.queryCardBatchByBatchMarkerNo(ct.getBatchMarkerNo());
			cb.setBackReceiver(activeUser.getUserNo().toString());
			try {
				cb.setBackRecDate(DateUtils.parseDate(vo.getReturnDate(), "yyyyMMdd"));
			} catch (ParseException e) {
				e.printStackTrace();
				String msg="日格格式化异常";
				logger.error(msg);
				throw new SystemException(SystemException.ParseException, msg);

			}
			cb.setFileName(vv.getFileName());
			cbm.update(cb);
		}
	}
	
	
	@Override
	public void applyAndGeneratCardMakeTask(List<String>list,ImportBankFileVo vv) throws Exception{
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Date now = new Date();
		List<Personal> lp = new ArrayList<>();
		for(String str:list){
			String [] info = StringUtils.splitPreserveAllTokens(str, "|");
			BankProvidePersonalVo vo = new BankProvidePersonalVo();
			vo.setPaperType(info[0]);
			vo.setPaperNo(info[1]);
			vo.setCustomerName(info[2]);
			vo.setGender(info[3]);
			vo.setNationality(info[4]);
			vo.setBirthday(info[5]);
			vo.setPrAddrDetailedInfo(info[6]);
			vo.setMobile(info[7]);
			vo.setCurAddrDetailedInfo(info[8]);
			vo.setCurPostalcode(info[9]);
			vo.setParentsLink(info[10]);
			vo.setSchoolName(info[11]);
			
			
			//申请
			Personal p =new Personal();
			p.setPaperType(vo.getPaperType());
			p.setPaperNo(vo.getPaperNo() );
			p.setCustomerName( vo.getCustomerName());
			p.setGender(p.getGender());
			p.setNationality(vo.getNationality());
			try {
				p.setBirthday(DateUtils.parseDate(vo.getBirthday(), "yyyyMMdd"));
			} catch (ParseException e) {
				e.printStackTrace();
				String msg="日格格式化异常";
				logger.error(msg);
				throw new SystemException(SystemException.ParseException, msg);

			}
			p.setPrAddrDetailedInfo(vo.getPrAddrDetailedInfo());
			p.setMobile(vo.getMobile());
			p.setCurAddrDetailedInfo(vo.getCurAddrDetailedInfo());
			p.setCurPostalcode(vo.getCurPostalcode());
			p.setParentsLink(vo.getParentsLink());
			p.setSchoolName(vo.getSchoolName());
			p.setApplyBatchNo(vv.getFileName());
			pm.savePersonal(p);
			lp.add(p);
		}
		
//		pm.batchInsert(lp);
		String prefix ="";
		String cardpCode="";
		String cardTypecod="";
		 CardProdunctDefinition cpd=null;
		 String copBankNo="";//合作银行编号
		if("JS_BANK".equalsIgnoreCase(vv.getBank())){
			 copBankNo = CardContants.CARD_PUBLISHER_CODE_JS;
			prefix ="1200";
			  cpd= cpdm.queryCardProdunctDefinitionByCardPublisherCode(copBankNo).get(0);
			 
		}else if("WF_BANK".equalsIgnoreCase(vv.getBank())){
			 copBankNo = CardContants.CARD_PUBLISHER_CODE_JS;
			prefix ="1100";
			 cpd=cpdm.queryCardProdunctDefinitionByCardPublisherCode(copBankNo).get(0);
		}
		cardpCode = cpd.getCardpCode();
		cardTypecod = cpd.getCardTypeCode();
		
		
		
		BatchCollection bc = new BatchCollection();
		bc.setApplyBatchNo(vv.getFileName());
		bc.setCardPCode(cardpCode);
		bc.setCollBranchName(activeUser.getBranchName());// 采集网店名称
		bc.setCollBranchNo(activeUser.getBranchNo());// 采集网点编号
		bc.setCrtDate(now);
		bc.setCrtOperator(activeUser.getUserNo().toString());
		bc.setLastDate(now);
		bc.setLastOperator(activeUser.getUserNo().toString());
		 bc.setOriginType(CardContants.DATA_ORIGIN_INPUT_BY_BANK);// 来源，后面可能要改成code1,code2...
		bc.setRecordNum(lp.size());// 记录申请数量
		Calendar ccc = Calendar.getInstance();
		ccc.setTime(now);
		ccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期
		bc.setApplyDate(ccc.getTime());
		bcm.saveBCollection(bc);
		
		List<CardData> list_CardData = new ArrayList<>();
		List<CardManage> list_CardManage = new ArrayList<>();
		List<Business> list_Business = new ArrayList<>();

		List<CardControl> list_CardControl = new ArrayList<>();
		
		List<Cert> list_Cert = new ArrayList<>();
			int flag = 0;
		for(Personal p:lp){
			flag++;
			
			//卡数据
//			String citizenCardNo = acs.generatorCardNo(prefix,cardpCode);
			CardData c = new CardData();
			c.setCustomerNo(p.getCustomerNo());// 客户编号
//			c.setCitizenCardNo(citizenCardNo);// 市民卡号
			c.setCardpCode(cardpCode);// 卡产品
			c.setCardTypecode(cardTypecod);// 卡类型
			c.setCardValidTime(CommonUtil.willDate(now, cpd.getCardValidTime()));
			c.setCopBankNo(copBankNo);
			c.setFlag(flag);
			list_CardData.add(c);
			
			
			Business b = new Business();
			b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
			b.setBatchNo(vv.getFileName());// 批次号
			b.setCustomerNo(p.getCustomerNo());
			b.setCardpCode(cardpCode);// 卡产品
			b.setRemark("這是批量申請業務表");// 备注
			b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
			b.setFlag(flag);
// 			b.setCardControlId(cardControlId);
			list_Business.add(b);
			
			CardManage cme = new CardManage();
			cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			cme.setApplyBranch(activeUser.getBranchName());
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(now);
			cme.setApplyTellerNo(activeUser.getUserNo().toString());
			cme.setBusinessNo(b.getBusinessNo());
//			cme.setCitizenCardNo(citizenCardNo);
			cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cme.setFlag(flag);
			list_CardManage.add(cme);
			
			Calendar cccc = Calendar.getInstance();
			cccc.setTime(now);
			cccc.add(Calendar.DAY_OF_MONTH, bpm.queryBusiParamByCardPCode(cardpCode).getReleaseDays());// 今天+n天===预计领卡日期

			
			// 卡控制信息
			CardControl cc = new CardControl();
//		cc.setCardDataId(c.getCardDataId());
			cc.setApplyDate(ccc.getTime());// 预计林卡日期
			cc.setCurrProcId(cme.getProcessId());
			// cc.setCardDate(cardDate);//制卡日期
			cc.setCardPosition(CardContants.CARD_POSITION_NO_STORAGE);// 位置未入库，还没生产呢
			cc.setCardStatus(CardContants.CARD_STATE_DISABLED);// 卡状态未启用
			cc.setApplyBatchNo(p.getApplyBatchNo());
			cc.setCrtDate(now);
			cc.setCrtOperator(activeUser.getUserNo().toString());
			cc.setLastDate(now);
			cc.setLastOperator(activeUser.getUserNo().toString());
			cc.setDmgFlag(CardContants.CARD_UNDAMAGED);// 卡损坏状况
														// 0-未损坏，1-非人为损坏，2-人为损坏
			// cc.setLogoutDate(logoutDate);//注销日期
			// cc.setLogoutReason(logoutReason);//注销原因

			// cc.setReleaseDate(ccc.getTime());//发卡日期
			cc.setRemark("这是备注--卡控制表");
			cc.setApplyType(CardContants.APPLY_TYPE_FIRST);
			cc.setClaimStatus(CardContants.CLAIM_STATUS_APPLY);
			cc.setFlag(flag);
			list_CardControl.add(cc);
			
			// 凭证表
			Cert ce = new Cert();
			ce.setCertNo(SequenceNumberUtil.generatorCertNo());
			// ce.setAgentName(agentName);//代领人的信息，领卡的时候在填写
			// ce.setAgentPaperNo(agentPaperNo);
			// ce.setAgentPapertype(agentPapertype);
			ce.setBranch(activeUser.getBranchName());// 网点名称
			ce.setBranchNo(activeUser.getUserNo().toString());// 网点编号
			 ce.setBusinessNo(b.getBusinessNo());//业务流水号
//		 ce.setCardControlId(cc.getCardControlId());
			ce.setCertType(CardContants.BATCH_APPLICATION);// 凭证类型 1 单笔申请 2 批量申请
															// 3 出库配送 4 单笔发卡 5
															// 批量发卡
			ce.setCardpCode(cardpCode);// 卡产品代码
			ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
														// 3.非记名衍生卡
//						ce.setCorpCode(cor.getCorpCode());// 单位编号id
//						ce.setCorpName(cor.getCorpName());// 单位名称
			ce.setCrtDate(now);
			ce.setCrtOperator(activeUser.getUserNo().toString());
			ce.setData("打印凭证数据 ");// 打印凭证数据
			ce.setLastDate(now);
			ce.setLastOperator(activeUser.getUserNo().toString());
			 ce.setName(p.getCustomerName());// 持卡人姓名
			 ce.setPaperNo(p.getPaperNo());
			 ce.setPaperType(p.getPaperType());
			ce.setPrintCount(0);// 打印次数
			// ce.setTransCode(transCode);//交易代码
			
			ce.setFlag(flag);
			list_Cert.add(ce);
			
		
		}
		
		
		CardData cd_q = cdm.queryNewestObject(cardpCode);
		List<String> list_CitizenCardNo = new ArrayList<>();
		if(cd_q == null){
			int valid = CardUtil.calcLuhn(prefix+"0000001");
			list_CitizenCardNo.add(prefix + valid + "0000001");
		}else{
			list_CitizenCardNo.add(acs.generatorCardNo(prefix,cd_q));
			
		}
		acs.generatorCardNo_list(prefix, list_CitizenCardNo, lp.size());
		for(int i=0;i<list_CitizenCardNo.size();i++){
			logger.debug("【{}】生成的卡号【{}】",i+1,list_CitizenCardNo.get(i));
			b:for(int j=0;j<list_CardData.size();j++){
				if(i == j){
					list_CardData.get(j).setCitizenCardNo(list_CitizenCardNo.get(j));
					break b;
				}
			}
			
		}
		
		cdm.batchInsert(list_CardData);
		
		for(CardData cd :list_CardData){
			b:for(CardControl cc:list_CardControl){
				if(cd.getFlag() == cc.getFlag()){
					cc.setCardDataId(cd.getCardDataId());
					break b;
				}
			}
			
			c:for(CardManage cm:list_CardManage){
				if(cd.getFlag() == cm.getFlag()){
					cm.setCitizenCardNo(cd.getCitizenCardNo());
					break c;
				}
			}
			
			
		}
		
		cmm.batchInsert(list_CardManage);
		
		cardm.batchInsert(list_CardControl);
		
		for(CardControl cc:list_CardControl){
			b:for(Cert c:list_Cert){
				if(cc.getFlag() == c.getFlag()){
					c.setCardControlId(cc.getCardControlId());
					break b;
				}
			}
		
			c:for(Business b:list_Business){
				if(cc.getFlag() == b.getFlag()){
					b.setCardControlId(cc.getCardControlId());
					break c;
				}
			}
			
		}
		logger.debug("---------业务数据【{}】",list_Business.size());
		bm.batchInsert(list_Business);
		cem.batchInsert(list_Cert);
		
		
		
		List<MakeCardQueryResultVo> listm = new ArrayList<>();
		MakeCardQueryResultVo mc = new MakeCardQueryResultVo();
		mc.setApplyNetDot(activeUser.getBranchName());
		mc.setNumber(list.size());
		mc.setTaskName(vv.getFileName());
		mc.setCardPName(cpd.getCardpName());
		mc.setApplyBatchNo(vv.getFileName());
		mc.setNumber(lp.size());
		mc.setCorp(copBankNo);
		listm.add(mc);
		
		GeneratCardMakeTask(listm);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void GeneratCardMakeTask(List<MakeCardQueryResultVo> list) {
		
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		int f=0;
		String prevTaskNO=null;//上一条任务编号
		List<CardProdunctDefinition> list_cpd = cpdm.queryCardProdunctDefinitionByValidStatus(CardContants.STATUS_ENABLE);
		for (MakeCardQueryResultVo mqv : list) {
			if(f==0){
				prevTaskNO=ctm.queryPreviousTaskNo();
				f++;
			}
			BatchCollection batchCollection=bcm.queryBatchCollectionByApplyBatchNo(mqv.getApplyBatchNo());
			CardTask ct = new CardTask();
			ct.setApplyBranch(batchCollection.getCollBranchName());// 申领网点名称
			ct.setApplyBranchNo(batchCollection.getCollBranchNo());// 申领网点编号
			// ct.setBatchMarkerNo(cb.getBatchMarkerNo());//制作批次号
			String cardTypeCode = "";
			for(CardProdunctDefinition cpd:list_cpd){
				if(cpd.getCardpName().equals(mqv.getCardPName())){
					ct.setCardpCode(cpd.getCardpCode());
					cardTypeCode = cpd.getCardTypeCode();
					break;
				}
			}
			
			ct.setCardTaskNo(SequenceNumberUtil.getSequenceNumber(ct.getCardpCode(), prevTaskNO));//制卡任务编号
			ct.setCardTypecode(cardTypeCode);// 卡类型代码
			if(StringUtils.isNotEmpty(mqv.getCompanyNo()))
			ct.setCompanyNo(mqv.getCompanyNo());

			// ct.setCorpCode(corpCode);//单位代码
			if(StringUtils.isNotEmpty(mqv.getCorp()))
			ct.setCorpName(mqv.getCorp());// 单位名称
			if(StringUtils.isNotEmpty(mqv.getDesc()))
			ct.setIsUrgent(mqv.getDesc());// 是否加急
			ct.setRecordNum(mqv.getNumber());// 记录数量
			ct.setRemark("这是制卡任务表的备注哦");// 备注
			// ct.setRollbackDate(rollbackDate);//回退日期
			// ct.setRollbackSn(rollbackSn);//回退日志流水号
			// ct.setRollbackStatus(rollbackStatus);//回退标志
			ct.setTaskName(mqv.getApplyBatchNo());// 任务名称
			ct.setTaskPerType(CardContants.EXECUTION_MODE_OUTSOURCE);// 任务执行方式
																		// 外包 本地
			ct.setTasksGeneTime(new Date());// 任务产生时间
			ct.setTasksOperator(activeUser.getUserNo().toString());//
			
			ct.setTaskStatus(CardContants.TASK_GENERATION);// 任务状态
			ct.setTaskType(CardContants.TASK_TYPE_NAME_CARD);// 任务类型 1-记名卡任务
			prevTaskNO=	ct.getCardTaskNo();												// 2-不记名任务
			ctm.insert(ct);
			
			List<CardControl> lc = cardm.queryCardControlByApplyBatchNo(mqv.getApplyBatchNo());
			
			List<CardData> cardDatas = cdm.queryCardDataByApplyBatchNo_list(mqv.getApplyBatchNo());
		
			
			List<Business>  lbu = new ArrayList<>();
			List<CardManage> lcm= new ArrayList<>();
			List<CardControl> lcc= new ArrayList<>();
			for (CardControl cc : lc) {
				
//				String citizenCardNo ="";
				// 业务流水表
				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
//				b.setBatchNo(apply);// 批次号
				b.setBusiNum(lc.size());// 业务数量啥子吆
				b.setCardControlId(cc.getCardControlId());//  
				b.setCardpCode(ct.getCardpCode());// 卡产品
				// b.setCertNo(certNo);/凭证编号
				
//				b.setCorpNo(cor.getCorpNo());// 单位编号 批量办理时使用
				for(CardData cr:cardDatas){
					if(cr.getCardDataId() == cc.getCardDataId()){
						b.setCustomerNo(cr.getCustomerNo());// 客户编号
//						citizenCardNo = cr.getCitizenCardNo();
						break;
					}
				}
				
				b.setRemark("這是批量申請業務表");// 备注
				// b.setRptDate(rptDate);//轧帐日期
				// b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
				b.setTransAuthId("业务授权人编号001");// 业务授权人编号
				b.setTransAuthName("业务授权人编号-赵铁柱");// 业务授权人姓名
				// b.setTransCode(transCode);//交易代码
				// b.setTransDate(transDate);//交易日期
				//
				lbu.add(b);
				
				CardManage cme = new CardManage();
				cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(new Date());
				cme.setApplyTellerNo(activeUser.getUserNo().toString());
//				cme.setProcessCode(CardContants.CARD_PROC_CARD_PEND);
//				cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_CARD_PEND));
//				cme.setCitizenCardNo(citizenCardNo);
				cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				cme.setBusinessNo(b.getBusinessNo());
				
				
				lcm.add(cme);
				
				cc.setCurrProcId(cme.getProcessId());// 申领状态：待制卡
				cc.setLastDate(new Date());
				cc.setLastOperator(activeUser.getUserNo().toString());
				cc.setCardTaskNo(ct.getCardTaskNo());
				cc.setClaimStatus(CardContants.CLAIM_STATUS_CARD_PEND);
				// cc.setCardPosition(CardContants.CARD_MAKE_ROOM);//卡位置：制卡间
				lcc.add(cc);
			}
			
			bm.batchInsert(lbu);
			cmm.batchInsert(lcm);
			
			cardm.batchUpdate(lcc);
			
		}

	}

	@Override
	public List<CooperationCompany> queryCooperationCompanyByType(
			String companyType) throws ApplicationException {
		if (StringUtils.isEmpty(companyType)) {
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL,
					"companyType is null!!!");
		}
		return ccm.queryCooperationCompanyByType(companyType);
	}


	private Set<String> exceptions(List<MakeCardQueryResultVo> list) throws ApplicationException{
		if(list.size()<0){
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "data  is  null!!!");
		}
		Set<String> set = new HashSet<>();//卡产品
		Set<String> set1 = new HashSet<>(); //制卡单位
		Set<String> set2 = new HashSet<>(); // 卡物理类型
		for (MakeCardQueryResultVo mqv : list) {
			set.add(mqv.getCardPName());
			set1.add(mqv.getCorp());
			set2.add(mqv.getCardPhysicsTypeCode());
		}
		
		if(set.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,cardP   do not match!!!");
		}
		
		if(set1.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,make card unit or bank  do not match!!!");
		}
		
		if(set2.size()>1){
			throw new ApplicationException(ErrorCode.DATA_NOT_MATCH, "data more than 1,cardPhysicalType  do not match!!!");
		}
		return set1;
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public List<String> exportMakeCardFile(String root,List<MakeCardQueryResultVo> list) throws ApplicationException {
		List<String> paths = new ArrayList<>();
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Date now = new Date();
		
		Set<String> set1 = exceptions(list); 
		CardBatch cb1 = cbm.queryFirstCardBatch();
		CardData cd =cdm.queryCardDataByCardTaskNo(list.get(0).getCardTaskNo());
//		String citizenCardNo =cd.getCitizenCardNo();
//		String prefix = citizenCardNo.substring(0, 4);
		
		String publisher = "10";

		List<CooperationCompany> list_CooperationCompany = cocm.queryCooperationCompanyByType(CardContants.COOPERATOR_CARD_FACTORY);
		 
		
		
		StringBuffer sb = new StringBuffer();
		for (MakeCardQueryResultVo mqv : list) {
			
			String batchMarkerNo = SequenceNumberUtil.generatorCardBatchKey(cb1);
			//文件名
			String fileName_pre = "RJMK10"+mqv.getCardPhysicsTypeCode()+"0"+batchMarkerNo;
			String fileName =fileName_pre +".txt";
			CardBatch cb = new CardBatch();
			
			
			 cb.setBatchMarkerNo(batchMarkerNo);//制作批次号  yyMMdd+4位序号
			cb.setDataReceiver(CardContants.COOPERATOR_CARD_FACTORY);// 数据接收方 就是 银行、制卡商
			cb.setDataSendDate(now);// 数据发送日期
			cb.setDataSender(activeUser.getUserNo().toString());// 数据发送人
			cb.setExportNum(1);// 导出次数
			
			if("10".equals(publisher)){
				cb.setFileName(fileName);//文件名
				cb.setPerformType(CardContants.EXECUTION_MODE_LOCAL);// 执行方式
				cb.setDataReceiver(CardContants.COOPERATOR_CARD_FACTORY);// 数据接收方 就是 银行、制卡商
			}
			
//			else if("11".equals(publisher) || "12".equals(publisher)){
//				cb.setFileName(list.get(0).getTaskName());
//				cb.setPerformType(CardContants.EXECUTION_MODE_OUTSOURCE);// 执行方式
//				cb.setDataReceiver(CardContants.COOPERATOR_BANK);// 数据接收方 就是 银行、制卡商
//			}
			String companyName = "";
		for(CooperationCompany cp:list_CooperationCompany){
			if(mqv.getCorp().equals(cp.getCompanyName())){
				cb.setSupplierCode(cp.getCompanyNo());//制卡厂商编号
				companyName = cp.getCompanyName();
				break;
			}
		}
			
				 
			
			cbm.insert(cb);
			cb1 = cb;
			
			
			
			
			
			

			CardTask ct = ctm.queryCardTaskByCardTaskNo(mqv.getCardTaskNo());
			if("10".equals(publisher)){
				ct.setTaskStatus(CardContants.EXPORTED_CARD_FILE);

			}
			
//			else if("11".equals(publisher) || "12".equals(publisher)){
//				ct.setTaskStatus(CardContants.DELIVERY_BANK);
//
//			}

			
			ct.setBatchMarkerNo(cb.getBatchMarkerNo());
			ctm.updateCardTask(ct);
			List<CardControl> lc = cardm.queryCardControlByApplyBatchNo(mqv.getApplyBatchNo());
			List<CardData> lcd  = cdm.queryCardDataByApplyBatchNo_list(mqv.getApplyBatchNo());
			List<CardManage> lcm = new ArrayList<>();
			List<Business> lbu =  new ArrayList<>();
			for (CardControl cc : lc) {
				if("10".equals(publisher)){
					cc.setClaimStatus(CardContants.CLAIM_STATUS_MAKING);

				}
				
//				else if("11".equals(publisher) || "12".equals(publisher)){
//					cc.setClaimStatus(CardContants.CLAIM_STATUS_BANK);
//
//				}
				cc.setLastDate(now);
				cc.setLastOperator(activeUser.getUserNo().toString());
				
				
				CardManage cme = new CardManage();
				cme.setProcessId(SequenceNumberUtil.generatorBusinessNo());
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(new Date());
				cme.setApplyTellerNo(activeUser.getUserNo(). toString());
//				cme.setProcessCode(CardContants.CARD_PROC_MAKING);
//				cme.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_MAKING));
				for(CardData card:lcd){
					if(cc.getCardDataId().equals(card.getCardDataId())){
						cme.setCitizenCardNo(card.getCitizenCardNo());
						break;
					}
				}
				
				cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				lcm.add(cme);
				
				
				// 业务流水表

				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
				// b.setAgentName(agentName);//代理人姓名
				// b.setAgentPaperNo(agentPaperNo);//代理人证件号码
				// b.setAgentPapertype(agentPapertype);//代理人证件类型
				// b.setAgentPhone(agentPhone);// 代理人联系电话
				 b.setBatchNo(cb.getBatchMarkerNo());//批次号
				b.setBusiNum(lc.size());// 业务数量
				b.setCardControlId(cc.getCardControlId());// 卡控制号
				b.setCardpCode(cdm.queryCardDataById(cc.getCardDataId()).getCardpCode());// 卡产品
//				b.setCertNo(ce.getCertNo());// 凭证编号
				// b.setCorpNo(corpNo);//单位编号 批量办理时使用
				b.setCustomerNo(cdm.queryCardDataById(cc.getCardDataId()).getCustomerNo());// 客户编号
				b.setRemark("当前业务流水");// 备注
				// b.setRptDate(rptDate);//轧帐日期
				// b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
				b.setTransAuthId("业务授权人编号001");// 业务授权人编号
				b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
				 b.setTransCode("交易代码");//
				 b.setTransDate(new Date());//交易日期
				b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况
				lbu.add(b);
				
				cc.setCurrProcId(cme.getProcessId());
				cc.setCardPosition(CardContants.CARD_MAKE_ROOM);// 卡位置：制卡间
			}
			
			
			cmm.batchInsert(lcm);
			bm.batchInsert(lbu);
			cardm.batchUpdate(lc);
			
			
			
			//制卡文件内容
			sb.append(queryMakeCardInfo(mqv.getCardTaskNo(),CardContants.CARD_TYPE_REGISTERED));
			
			
			String fileProjectpath ="";
			//导出制卡文件
//			if("10".equals(publisher)){
				 fileProjectpath =PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+companyName+File.separator+fileName_pre+File.separator+fileName;
				FileUtil.contentToTxt(root.split("\\|")[0]+fileProjectpath, sb.toString(), FileUtil.str);
				String zipName= fileName_pre+".zip";
				String zipPath = root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+companyName+File.separator+zipName;
				ZipUtil.createZip(root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+companyName+fileName_pre, zipPath);

				paths.add(root.split("\\|")[1]+ PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+companyName+File.separator+zipName);
//			}
		}
		
//		
		 return paths;
	}

	@Override
	public DwzPage<MakeCardQueryResultVo> queryCardTask(
			MakeCardQueryConditionVo mcv) {
		mcv.setTaskStatus(CardContants.TASK_GENERATION);
		List<CardTask> list = ctm.queryCardTask(mcv);
		
		List<MakeCardQueryResultVo> ll = new ArrayList<>();
		for (CardTask c : list) {
			logger.debug("查询任务【{}】",c.getCardTaskNo());
			MakeCardQueryResultVo m = new MakeCardQueryResultVo();
			m.setCardPName(cpdm.queryCardPCode(c.getCardpCode()).getCardpName());
			m.setTaskName(c.getTaskName());
			m.setApplyNetDot(c.getApplyBranch());
			m.setCardTaskNo(c.getCardTaskNo());
			if(StringUtils.isNotEmpty(c.getCompanyNo()))
			m.setCorp(cocm.queryCooperationCompanyByCompanyNo(c.getCompanyNo())
					.getCompanyName());
			m.setDesc(c.getIsUrgent());
			m.setNumber(c.getRecordNum());
			m.setTasksGeneTime(c.getTasksGeneTime());
			
			//String citizenCardNo = cdm.queryCardDataByCardTaskNo(c.getCardTaskNo()).getCitizenCardNo();
			//String cardPhysicsTypeCode = String.valueOf(citizenCardNo.charAt(2));
			CardData cardData=cdm.queryCardDataByCardTaskNo(c.getCardTaskNo());
			String cardPhysicsTypeCode=cardData.getCardPhysicalType();
			m.setCardPhysicsTypeCode(cardPhysicsTypeCode);
			CardPhysicsType cpt = cptm.queryCardPhysicsTypeByCode(cardPhysicsTypeCode);
			m.setCardPhysicsTypeName(cpt.getCardTypeName());
			
			
			ll.add(m);
		}
		int totalCount = ctm.querytotalCountByTaskType(mcv);
		DwzPage<MakeCardQueryResultVo> dp = new DwzPage<MakeCardQueryResultVo>(
				mcv.getCurrentPage(), mcv.getNumPerPage(), totalCount);
		dp.setList(ll);
		return dp;
	}

	//批量生成卡号
	private static List<String> getEnd(String prefix,String end,int count,List<String> l){
		Integer e = Integer.valueOf(end);
		String new_end = CitizenCardNoGeneratorUtil.generatorSeq(String.valueOf(e+1), 7);
		int valid = CardUtil.calcLuhn(prefix+new_end);
		String cardNo = prefix+ valid+new_end;
		
		l.add(cardNo);
		if(count == 0 ){
			return l;
		}
		return getEnd(prefix,new_end,count-1,l);
	}
	
	public static void main(String[] args) throws Exception {
		Integer a =1;
		Integer b = 1;
		System.out.println(a== b);
		
		List<String> l1 = new ArrayList<>();
		 l1 = getEnd("1000","0000001", 10,l1);
		for(String s:l1){
			System.out.println(s);
			System.out.println(CardUtil.verifyCardNo(s));
		}
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public void GeneratCardMakeTask1(MakeCardParamVo mcpv) throws Exception {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		String prevTaskNO=ctm.queryPreviousTaskNo();//上一个任务编号
		CardTask ct = new CardTask();
		ct.setCardTaskNo(SequenceNumberUtil.getSequenceNumber(mcpv.getCardPCode(),prevTaskNO));//制卡任务编号
		ct.setApplyBranchNo(activeUser.getBranchNo());// 申领网点编号
		ct.setApplyBranch(activeUser.getBranchName());// 申领网点名称
		// ct.setBatchMarkerNo(cb.getBatchMarkerNo());//制作批次号
		ct.setCardpCode(mcpv.getCardPCode());
		
		ct.setCardTypecode(cpdm.queryCardPCode(mcpv.getCardPCode()).getCardTypeCode());// 卡类型代码
		ct.setCompanyNo(mcpv.getMakeCardCorpNo());// 制卡厂商编号

		// ct.setCorpCode(corpCode);//单位代码
		// ct.setCorpName(mqv.getCorp());//单位名称
		ct.setIsUrgent(mcpv.getIsUrgent());// 是否加急
		ct.setRecordNum(mcpv.getCount());// 记录数量
		ct.setRemark("不记名制卡任务生成");// 备注
		// ct.setRollbackDate(rollbackDate);//回退日期
		// ct.setRollbackSn(rollbackSn);//回退日志流水号
		// ct.setRollbackStatus(rollbackStatus);//回退标志
		ct.setTaskName(mcpv.getTaskName());// 任务名称
		ct.setTaskPerType(CardContants.EXECUTION_MODE_OUTSOURCE);// 任务执行方式 外包 本地
		ct.setTasksGeneTime(new Date());// 任务产生时间
		ct.setTasksOperator(activeUser.getUserNo().toString());//
		ct.setTaskStatus(CardContants.TASK_GENERATION);// 任务状态
		ct.setTaskType(CardContants.TASK_TYPE_NO_NAME_CARD);// 任务类型 1-记名卡任务
															// 2-不记名任务
		//
		ctm.insert(ct);
 		List<CardManage> cardManage_list = new ArrayList<>();
		List<CardControl> cardControl_list = new ArrayList<>();
		
/*		CardData cdaa = cdm.queryNewestObject(mcpv.getCardPCode());
		String prefix = CitizenCardNoGeneratorUtil.getCardNoPrefix(mcpv.getCardPCode(), mcpv.getCardPhysicalType());
		String citizenCardNo1 ="";
		String end ="";
		if (cdaa == null) {
			int valid = CardUtil.calcLuhn("0000001");
			citizenCardNo1 = prefix + valid + "0000001";
			end = "0000001";
		}else{
			citizenCardNo1 = cdaa.getCitizenCardNo();
			end =citizenCardNo1.substring(5);
		}
		*/
		List<CardProdunctDefinition> list_cpd = cpdm.queryCardProdunctDefinitionByValidStatus(CardContants.STATUS_ENABLE);
		
		//区分不记名卡和空白卡
		CardProdunctDefinition cardProdunctDefinition=null;
		Iterator<CardProdunctDefinition> iterator2=list_cpd.iterator();
		while(iterator2.hasNext()){
			CardProdunctDefinition cDefinition=iterator2.next();
			if(cDefinition.getCardpCode().equals(mcpv.getCardPCode())){
				cardProdunctDefinition=cDefinition;
				break;
			}
		}
		if(cardProdunctDefinition==null){
			throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "此卡产品未启用");
		}
		
		List<String>cardNos=null;
		//不记名卡
		if(cardProdunctDefinition.getCardTypeCode().equals(CardContants.CARD_TYPE_ANONYMOUS)){
			List<CardNoGenerated>cardNoGenerateds=cardNoGeneratedMapper.queryAllRecordByCardpCode(mcpv.getCardPCode());
			//未使用完的卡号库
			Iterator<CardNoGenerated> iterator=cardNoGenerateds.iterator();
			//移除不同物理卡类型的卡号库
			while(iterator.hasNext()){
				CardNoGenerated cardNoGenerated=iterator.next();
				if(!mcpv.getCardPhysicalType().equals(cardNoGenerated.getCardPhysicalType())){
					iterator.remove();
				}
			}
			if(cardNoGenerateds.isEmpty()){
				throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "卡号库为空，请先生成卡号库");
			}
			if(cardNoGenerateds.size()>1){
				Collections.sort(cardNoGenerateds,new Comparator<CardNoGenerated>() {
					@Override
					public int compare(CardNoGenerated o1, CardNoGenerated o2) {
						int a=Integer.parseInt(o1.getStartSegmentNo());
						int b=Integer.parseInt(o2.getStartSegmentNo());
						if(a<b){
							return -1;
						}else{
							return 1;
						}
						
					}
				});
			}
			//frist卡号后7位
			String startNumber=CommonUtil.patchHexString(String.valueOf(Integer.valueOf(cardNoGenerateds.get(0).getStartSegmentNo()).intValue()+cardNoGenerateds.get(0).getUsedSegmentNo()), 7);
			String prefix=CitizenCardNoGeneratorUtil.getCardNoPrefix(mcpv.getCardPCode(),mcpv.getCardPhysicalType());
			//获取卡号列表
			cardNos=CitizenCardNoGeneratorUtil.generatorCitizenCardNo(mcpv.getCount().intValue(), startNumber, prefix);
			//last卡号后7位
			String endNumber=CommonUtil.patchHexString(String.valueOf(Integer.valueOf(startNumber).intValue()+ct.getRecordNum().intValue()-1), 7);
			int counter=0;
			//更新文件
			for(int i=0;i<cardNoGenerateds.size();i++){
				if(Integer.valueOf(endNumber).intValue()<=Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()){
					CardNoGenerated cardNoGenerated=new CardNoGenerated();
		    		cardNoGenerated.setId(cardNoGenerateds.get(i).getId());
					cardNoGenerated.setUsedSegmentNo(cardNoGenerateds.get(i).getUsedSegmentNo()+ct.getRecordNum().intValue()-counter);
					cardNoGenerated.setIsUseUp(Integer.valueOf(endNumber).intValue()==Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()?"1":"0");				
					cardNoGeneratedMapper.updateByPrimaryKey(cardNoGenerated);
					break;
				}else{
					CardNoGenerated cardNoGenerated=new CardNoGenerated();
		    		cardNoGenerated.setId(cardNoGenerateds.get(i).getId());
					cardNoGenerated.setUsedSegmentNo(Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()-Integer.valueOf(cardNoGenerateds.get(i).getStartSegmentNo())+1);
					cardNoGenerated.setIsUseUp("1");				
					cardNoGeneratedMapper.updateByPrimaryKey(cardNoGenerated);
					counter+=cardNoGenerated.getUsedSegmentNo();
					continue;
				}
			}
		}
		
		
		int flag = 0;
		List<CardData> cardData_list = new ArrayList<>();
		for (int i = 0; i < mcpv.getCount(); i++) {
			flag++;
			CardData cd = new CardData();
			cd.setCardpCode(mcpv.getCardPCode());
			if(cardProdunctDefinition.getCardTypeCode().equals(CardContants.CARD_TYPE_ANONYMOUS)){
				cd.setCitizenCardNo(cardNos.get(i));
			}
			//20181217 hgl 增加以下一行
			cd.setCardPhysicalType(mcpv.getCardPhysicalType());
			for(CardProdunctDefinition cpd:list_cpd){
				if(cpd.getCardpCode().equals(mcpv.getCardPCode())){
					cd.setCardTypecode(cpd.getCardTypeCode());
					break;
				}
			}
			
			cd.setFlag(flag);
			cardData_list.add(cd);
			
			CardManage cme = new CardManage();
			cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			cme.setApplyBranch(activeUser.getBranchName());
			cme.setApplyBranchNo(activeUser.getBranchNo());
			cme.setApplyDate(new Date());
			if(cardProdunctDefinition.getCardTypeCode().equals(CardContants.CARD_TYPE_ANONYMOUS)){
				cme.setCitizenCardNo(cardNos.get(i));
			}
			cme.setApplyTellerNo(activeUser.getUserNo().toString());
			cme.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
			cardManage_list.add(cme);
			
			CardControl cc = new  CardControl();
			cc.setClaimStatus(CardContants.CLAIM_STATUS_MAKING);
			cc.setCardStatus(CardContants.CARD_STATE_DISABLED);
			cc.setCurrProcId(cme.getProcessId());;// 申领状态：制卡
			cc.setCardPosition(CardContants.CARD_MAKE_ROOM);// 卡位置：制卡间
			cc.setCardTaskNo(ct.getCardTaskNo());
			cc.setFlag(flag);
			cardControl_list.add(cc);
			
		}
/*		List<String> list_cardNo = new ArrayList<>();
				list_cardNo = getEnd(prefix, end, mcpv.getCount(), list_cardNo);
		for(int j=0;j<list_cardNo.size();j++){
			for(int i=0;i<cardData_list.size();i++){
				if(i == j){
					cardData_list.get(i).setCitizenCardNo(list_cardNo.get(j));
					break;
				}
			}
			
			for(int a=0;a<cardManage_list.size();a++){
				if(a == j){
					cardManage_list.get(a).setCitizenCardNo(list_cardNo.get(j));
					break;
				}
			}
			
		}
	*/	
		cdm.batchInsert(cardData_list);
		cmm.batchInsert(cardManage_list);
		
		
/*		
		for(int i=0;i<cardData_list.size();i++){
			for(int j=0;j<cardControl_list.size();j++){
				if(i==j){
					cardControl_list.get(j).setCardDataId(cardData_list.get(i).getCardDataId());
					break;
				}
			}
		}
*/		
		for(CardData cardData:cardData_list){
			a:for(CardControl cardControl : cardControl_list){
				if(cardData.getFlag() == cardControl.getFlag()){
					cardControl.setCardDataId(cardData.getCardDataId());
					break a;
				}
			}
		}
		cardm.batchInsert(cardControl_list);
		
		
		
		
		
		
		//保存任务名
		
		ApplyBatchRecord abr = new ApplyBatchRecord();
		abr.setCardpCode(mcpv.getCardPCode());
		abr.setCardPhysicalType(mcpv.getCardPhysicalType());
		abr.setDate(new Date());
		abr.setDesc("空白卡申请任务");
		String no = mcpv.getTaskName();
		abr.setBatchNo(no);
		abr.setSeq(no.substring(no.lastIndexOf("_")+1));
		abrm.insert(abr);
	}
	
	
	@Override
	public String queryMakeCardInfo(String cardTaskNo,String cardType) {
		StringBuffer sb = new StringBuffer();
		if(CardContants.CARD_TYPE_ANONYMOUS.equals(cardType)){
			
			List<CardData> queryCardData_list = cdm.queryCardDataByCardTaskNo_list(cardTaskNo);
			for(int i=0;i<queryCardData_list.size();i++){
//				String citizenCardNo = queryCardData_list.get(i).getCitizenCardNo();
				String cardpCode = queryCardData_list.get(i).getCardpCode();
				MakeCardInfo mci = new MakeCardInfo();			
				//卡片信息
//				String acsCitizenCardNo = CommonUtil.stringToAscii(citizenCardNo); //长度24
				
//				String end8 = citizenCardNo.substring(4);
				
//				String appSeqNo = CardContants.CITY_CODE+ CommonUtil.stringToAscii(end8) ;//以下的所有应用序列号  2625+卡面号后8字节ascii
				
				 cardpCode=Integer.toHexString(Integer.valueOf(cardpCode)).toUpperCase();//卡类型  就是卡产品代码转16进制 
				if(cardpCode.length() == 1 ){
					cardpCode = "0"+cardpCode;
				}
				mci.cardholderType_3F000005=cardpCode;//3F00.0005.卡主类型
//				mci.setCitizenCardNo_3F000005(acsCitizenCardNo);//3F00.0005.市民卡卡号   长度24
//				mci.setApplicationSequenceNumber_3F010015(appSeqNo);//3F01.0015.应用序列号     2625+卡面号后8字节ascii
				mci.cardType_3F010015=cardpCode;// 3F01.0015.卡类型
//				mci.setApplicationSequenceNumber_3F020015(appSeqNo);//3F02.0015.应用序列号
				mci.setCardType_3F020015("00");//3F02.0015.卡类型
//				mci.setApplicationSequenceNo_3F100015(appSeqNo);//3F10.0015.应用序列号
//				mci.setApplicationSequenceNumber_9A000015(appSeqNo);// 9A00.0015.应用序列号
				mci.setCardType_9A000015(cardpCode);//9A00.0015.卡类型
				if(i<queryCardData_list.size()-1){
					sb.append(mci.toString());
				}
				else if(i==queryCardData_list.size()-1){
					Pattern p = Pattern.compile("\r|\n");
			        Matcher m = p.matcher(mci.toString());
			        sb.append(m.replaceAll(""));
				}
			
			}

		}else if(CardContants.CARD_TYPE_REGISTERED.equals(cardType)){
			List<Personal> list = pm.queryPersonalByCardTaskNo1(cardTaskNo);
			for(Personal p:list){
				MakeCardInfo mci = new MakeCardInfo();
				//个人信息
				mci.setPaperType(p.getPaperType());//证件种类
				mci.setPaperNo(p.getPaperNo());//证件号码
				mci.setCustomerName(p.getCustomerName());//姓名
				mci.setGender(p.getGender());//性别
				
				mci.setNation(p.getNationality());//民族
				mci.setBirthday(DateFormatUtils.format(p.getBirthday(), "yyyyMMdd"));//出生日期
				mci.setPermanentAddress(p.getPrAddrProvince()+p.getPrAddrCity()+p.getCurAddrProvince());//户籍地址
				mci.setMobile(p.getMobile());//手机号
				mci.setHomeAddress(p.getCurAddr());//家庭地址 
				mci.setZipCode(p.getCurPostalcode());//邮政编码
//				mci.setParentMobile(p.getParentsLink());//家长手机号
//				mci.setSchool(p.getSchoolName());//所在学校
//				mci.setClazz(p.getClassName());//所在班级
				
				//卡片信息
				CardData cc = cdm.queryCardDataByCustomerNoAndCardTaskNo(p.getCustomerNo(), cardTaskNo);
//				String acsCitizenCardNo = CommonUtil.stringToAscii(cc.getCitizenCardNo()); //长度24
//				String end8 = cc.getCitizenCardNo().substring(4);
//				String appSeqNo = CardContants.CITY_CODE+ CommonUtil.stringToAscii(end8) ;//以下的所有应用序列号  2625+卡面号后8字节ascii
				
				String cardpCode=Integer.toHexString(Integer.valueOf(cc.getCardpCode())).toUpperCase();//卡类型  就是卡产品代码转16进制 cc
				if(cardpCode.length() == 1 ){
					cardpCode = "0"+cardpCode;
				}
				
				mci.cardholderType_3F000005=cardpCode;//3F00.0005.卡主类型
//				mci.setCitizenCardNo_3F000005(acsCitizenCardNo);//3F00.0005.市民卡卡号   长度24
				
//				mci.setCitizenCardvalidNo_3F000005(citizenCardvalidNo_3F000005);//3F00.0005.市民卡校验码
//				mci.setApplicationSequenceNumber_3F010015(appSeqNo);//3F01.0015.应用序列号     2625+卡面号后8字节ascii
				mci.cardType_3F010015=cardpCode;// 3F01.0015.卡类型
//				mci.setApplicationSequenceNumber_3F020015(appSeqNo);//3F02.0015.应用序列号
				mci.setCardType_3F020015("00");//3F02.0015.卡类型
//				mci.setApplicationSequenceNo_3F100015(appSeqNo);//3F10.0015.应用序列号
//				mci.setApplicationSequenceNumber_9A000015(appSeqNo);// 9A00.0015.应用序列号
				mci.setCardType_9A000015("00");//9A00.0015.卡类型
				sb.append(mci.toString());
			}
		}
			
			
		
		
		return sb.toString();
	}

	
	@Override
	public void modifyCardTaskByTaskNo(MakeCardParamVo mcpv) {
		ctm.modifyCardTaskByTaskNo(mcpv);
	}

	
	@Override
	public void deleteCardTasks(String[] cardTaskNos) {
		for(String cardTaskNo: cardTaskNos){
			cdm.deleteCardDataByCardTaskNO(cardTaskNo);//先卡数据表
			cardm.deleteCardControlByCardTaskNO(cardTaskNo);//后卡控制表
			ctm.deleteCardTask(cardTaskNo);//再任务表
		}
	}

	@Override
	public MakeCardParamVo queryCardTaskByTaskNo(String cardTaskNo ) throws ApplicationException {
		if(StringUtils.isEmpty(cardTaskNo)){
			throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "cardTaskNo or taskType  is  null !!!");
		}
		CardTask ct = ctm.queryCardTaskByCardTaskNo(cardTaskNo);
		MakeCardParamVo mcpv = new MakeCardParamVo();
		
		String cardpCode = ct.getCardpCode();
		mcpv.setCardPCode(cardpCode);
		mcpv.setCardPName(cpdm.queryCardPCode(cardpCode).getCardpName());
		
//		String citizenCardNo = cdm.queryCardDataByCardTaskNo(cardTaskNo).getCitizenCardNo();
//		String cardPhysicalType = String.valueOf(citizenCardNo.charAt(2));
		String cardPhysicalType=cdm.queryCardDataByCardTaskNo(cardTaskNo).getCardPhysicalType();
		mcpv.setCardPhysicalType(cardPhysicalType);
		String cardPhysicalTypeName = cptm.queryCardPhysicsTypeByCode(cardPhysicalType).getCardTypeName();
		mcpv.setCardPhysicalTypeName(cardPhysicalTypeName);
		
		String makeCardCorpNo = ct.getCompanyNo();
		mcpv.setMakeCardCorpNo(makeCardCorpNo);
		mcpv.setMakeCardCorpName(ccm.queryCooperationCompanyByCompanyNo(makeCardCorpNo).getCompanyName());
		
		mcpv.setCount(ct.getRecordNum());
		mcpv.setIsUrgent(ct.getIsUrgent());
		mcpv.setDesc(ct.getRemark());
		mcpv.setTaskName(ct.getTaskName());
		mcpv.setCardTaskNo(cardTaskNo);
		return mcpv;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public String queryMakeCardInfo1(CardTask ct) {
//		CardData cardData = cdm.queryCardDataByCardTaskNo(ct.getCardTaskNo());
		List<CardData> cardDatas=cdm.queryCardDataByCardTaskNo_list(ct.getCardTaskNo());
//		 String  cardType = citizenCardNo.substring(0, 3);
		MakeCardInfo2  m = new MakeCardInfo2();
		m.setCardTaskNo(ct.getCardTaskNo());
		//未使用完的卡号库
//		List<CardNoGenerated> cardNoGenerateds= cardNoGeneratedMapper.queryAllRecordByCardpCode(ct.getCardpCode());
//		Iterator<CardNoGenerated> iterator=cardNoGenerateds.iterator();
//		//移除不同物理卡类型的卡号库
//		while(iterator.hasNext()){
//			CardNoGenerated cardNoGenerated=iterator.next();
//			if(!cardData.getCardPhysicalType().equals(cardNoGenerated.getCardPhysicalType())){
//				iterator.remove();
//			}
//		}
//		Collections.sort(cardNoGenerateds,new Comparator<CardNoGenerated>() {
//			@Override
//			public int compare(CardNoGenerated o1, CardNoGenerated o2) {
//				int a=Integer.parseInt(o1.getStartSegmentNo());
//				int b=Integer.parseInt(o2.getStartSegmentNo());
//				if(a<b){
//					return -1;
//				}else{
//					return 1;
//				}
//				
//			}
//		});
//		//卡号后7位
//		String startNumber=CommonUtil.patchHexString(String.valueOf(Integer.valueOf(cardNoGenerateds.get(0).getStartSegmentNo()).intValue()+cardNoGenerateds.get(0).getUsedSegmentNo()), 7);
//		//卡号后7位
//		String endNumber=CommonUtil.patchHexString(String.valueOf(Integer.valueOf(startNumber).intValue()+ct.getRecordNum().intValue()-1), 7);
//		int counter=0;
//		//更新文件
//		for(int i=0;i<cardNoGenerateds.size();i++){
//			if(Integer.valueOf(endNumber).intValue()<=Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()){
//				CardNoGenerated cardNoGenerated=new CardNoGenerated();
//	    		cardNoGenerated.setId(cardNoGenerateds.get(i).getId());
//				cardNoGenerated.setUsedSegmentNo(cardNoGenerateds.get(i).getUsedSegmentNo()+ct.getRecordNum().intValue()-counter);
//				cardNoGenerated.setIsUseUp(Integer.valueOf(endNumber).intValue()==Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()?"1":"0");				
//				cardNoGeneratedMapper.updateByPrimaryKey(cardNoGenerated);
//				break;
//			}else{
//				CardNoGenerated cardNoGenerated=new CardNoGenerated();
//	    		cardNoGenerated.setId(cardNoGenerateds.get(i).getId());
//				cardNoGenerated.setUsedSegmentNo(Integer.valueOf(cardNoGenerateds.get(i).getEndSegmentNo()).intValue()-Integer.valueOf(cardNoGenerateds.get(i).getStartSegmentNo())+1);
//				cardNoGenerated.setIsUseUp("1");				
//				cardNoGeneratedMapper.updateByPrimaryKey(cardNoGenerated);
//				counter+=cardNoGenerated.getUsedSegmentNo();
//				continue;
//			}
//		}
//		//组装卡号
//		String prefix=CitizenCardNoGeneratorUtil.getCardNoPrefix(ct.getCardpCode(),cardData.getCardPhysicalType() );
//		int valid = CardUtil.calcLuhn(prefix+startNumber);
//		m.setStartNumber(prefix+valid+startNumber);
//		valid = CardUtil.calcLuhn(prefix+endNumber);
//		m.setStopNumber(prefix+valid+endNumber);
//		
//		m.setCityCode("2625");
//		Integer count  = ct.getRecordNum();
//		m.setRecordAmount(count.toString());
//		
//		m.setCardType(startNumber.substring(0, 4));
//		**************************************************************
		m.setCityCode("2625");
		Integer count  = ct.getRecordNum();
		m.setRecordAmount(count.toString());
		CardData cd =cardDatas.get(0);
		String startNumber =cd.getCitizenCardNo();
		m.setStartNumber(startNumber);
		cd=cardDatas.get(cardDatas.size()-1);
		m.setStopNumber(cd.getCitizenCardNo());
		
		m.setCardType(startNumber.substring(0, 4));
		
		
		
		return m.toString();
	}
	

	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public List<String> exportMakeCardFile1(String root,List<MakeCardQueryResultVo> list) throws ApplicationException {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		List<String> ls = new ArrayList<>();
		CardBatch cb1 = cbm.queryFirstCardBatch();

		
		 String companyName="";
		 Set<String> set1 = exceptions(list); 
		 Iterator<String> it = set1.iterator();
		 while(it.hasNext()){
			 companyName = it.next();
		 }
		 CooperationCompany ccom = cocm.queryCooperationCompanyByCompanyName(companyName);
		 String prefix="";
		for(MakeCardQueryResultVo mcv:list){
			String  cardTaskNo = mcv.getCardTaskNo();
			StringBuffer sb = new  StringBuffer();
//			List<CardControl> ll = cardm.queryCardControlByCardTaskNo(cardTaskNo);
//			List<CardData> lc =  cdm.queryCardDataByCardTaskNo_list(cardTaskNo);
			
			CardTask ct = ctm.queryCardTaskByCardTaskNo(cardTaskNo);
		
		String batchMarkerNo = SequenceNumberUtil.generatorCardBatchKey(cb1);
				
//		String citizenCardNo =lc.get(0).getCitizenCardNo();
//		String prefix = citizenCardNo.substring(0, 4);
		
		
		if(StringUtils.isEmpty(prefix)){
			 prefix ="10"+mcv.getCardPhysicsTypeCode()+"0";

		}
		
		//文件名
		String name_1="";
		String fileName="";
		if(CardContants.CARD_TYPE_ANONYMOUS.equals(ct.getCardTypecode())){
			name_1="RBJM"+prefix+batchMarkerNo;
		}else if(CardContants.CARD_TYPE_REGISTERED.equals(ct.getCardTypecode())){
			name_1 = "RJMK"+prefix+batchMarkerNo;   //不带个人信息
		}
		 fileName = name_1 +".txt";
		
		//保存制卡批次表
		CardBatch cb = new CardBatch();
		 cb.setBatchMarkerNo(batchMarkerNo);//制作批次号  yyMMdd+4位序号
		
		cb.setDataReceiver(ccom.getCompanyType());// 数据接收方 就是 银行、制卡商
		cb.setDataSendDate(new Date());// 数据发送日期
		cb.setDataSender(activeUser.getUserNo().toString());// 数据发送人
		cb.setExportNum(1);// 导出次数
		 cb.setFileName(fileName);//文件名
		cb.setPerformType(CardContants.EXECUTION_MODE_OUTSOURCE);// 执行方式
	
		cb.setSupplierCode(ccom.getCompanyNo());//制卡厂商编号

		cbm.insert(cb);
		cb1 = cb ;
		
			
			
			ct.setTaskStatus(CardContants.EXPORTED_CARD_FILE);
			ct.setBatchMarkerNo(cb.getBatchMarkerNo());
			ctm.updateCardTask(ct);
	/*		
			List<CardManage> cardManage_list = new ArrayList<>();
			List<CardControl> cardControl_list = new ArrayList<>();
			List<Business> business_list = new ArrayList<>();
			for(CardControl cc :ll){
				String cardPcode ="";
				CardManage cme = new CardManage();
				cme.setProcessId(UUID.randomUUID().toString().replace("-", ""));
				cme.setApplyBranch(activeUser.getBranchName());
				cme.setApplyBranchNo(activeUser.getBranchNo());
				cme.setApplyDate(new Date());
				cme.setApplyTellerNo(activeUser.getUserNo().toString());
				for(CardData ca:lc){
					if(ca.getCardDataId() == cc.getCardDataId()){
						cme.setCitizenCardNo(ca.getCitizenCardNo());
						cardPcode = ca.getCardpCode();
						break;
					}
				}
				
				cme.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);// 1.零星2.单位规模3.社区规模4.网上规模9.其他规模
				
				cardManage_list.add(cme);
				
				cc.setClaimStatus(CardContants.CLAIM_STATUS_MAKING);
				
				cc.setCurrProcId(cme.getProcessId());// 申领状态：制卡
				cc.setCardPosition(CardContants.CARD_MAKE_ROOM);// 卡位置：制卡间
				cardControl_list.add(cc);
				
				
				// 业务流水表

				Business b = new Business();
				b.setBusinessNo(SequenceNumberUtil.getBusSeq());
//				b.setBusiNum(1);// 业务数量
				b.setCardControlId(cc.getCardControlId());// 卡控制号
				b.setCardpCode(cardPcode);// 卡产品
//				b.setCertNo(ce.getCertNo());// 凭证编号
				// b.setCorpNo(corpNo);//单位编号 批量办理时使用
//				b.setCustomerNo(p.getCustomerNo());// 客户编号
				b.setRemark("导出制卡文件-不记名卡");// 备注
				// b.setRptDate(rptDate);//轧帐日期
				// b.setRptFlag(rptFlag);//轧帐标识
				b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
//				b.setTransAuthId("业务授权人编号001");// 业务授权人编号
//				b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
//				b.setTransCode("交易代码");//
				b.setTransDate(new Date());//交易日期
				b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况
				business_list.add(b);

			}
		*/	
			// 业务流水表

			Business b = new Business();
			b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
//			b.setBusiNum(1);// 业务数量
//			b.setCardControlId(cc.getCardControlId());// 卡控制号
			b.setCardpCode(ct.getCardpCode());// 卡产品
//			b.setCertNo(ce.getCertNo());// 凭证编号
			// b.setCorpNo(corpNo);//单位编号 批量办理时使用
//			b.setCustomerNo(p.getCustomerNo());// 客户编号
			b.setRemark("导出制卡文件-不记名卡");// 备注
			// b.setRptDate(rptDate);//轧帐日期
			// b.setRptFlag(rptFlag);//轧帐标识
			b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
//			b.setTransAuthId("业务授权人编号001");// 业务授权人编号
//			b.setTransAuthName("业务授权人姓名-赵铁柱");// 业务授权人姓名
//			b.setTransCode("交易代码");//
			b.setTransDate(new Date());//交易日期
			b.setSeqStatus(CardContants.LSZT_NORMAL);// 0.临时1.正常 2.撤销 3.冲正默认为1正常，目前暂时没有使用2撤销和3冲正的情况
			
			bm.insert(b);
			
//			cmm.batchInsert(cardManage_list);
//			cardm.batchUpdate(cardControl_list);
//			
//			bm.batchInsert(business_list);
			
			
			String mci = "";
			String[] title = FileUtil.str;
			if(CardContants.CARD_TYPE_ANONYMOUS.equals(ct.getCardTypecode())){
				mci = queryMakeCardInfo1(ct);
				title = FileUtil.str1;
			}else if(CardContants.CARD_TYPE_REGISTERED.equals(ct.getCardTypecode())){
				mci = queryMakeCardInfo(cardTaskNo,CardContants.CARD_TYPE_ANONYMOUS);
			}
			logger.debug("文件名称：【{}】",name_1);
			logger.debug("卡类型：【{}】",mci);
			sb.append(mci);
			String fileProjectpath =PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+"/"+name_1+"/"+fileName;
			
			FileUtil.contentToTxt(root.split("\\|")[0] + fileProjectpath, sb.toString(), title);
			String zipName= name_1+".zip";
			String zipPath = root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+zipName;
			ZipUtil.createZip(root.split("\\|")[0] + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+name_1, zipPath);
			ls.add(root.split("\\|")[1] +PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR+File.separator+zipName);
		}
		return ls;
	}
	
	@Override
	public DwzPage<CardNoGeneratedVo> queryCardNoDetail(CardNoGeneratedVo cardNoGeneratedVo) {
		List<CardNoGeneratedVo> list=cardNoGeneratedMapper.queryAllRecord(cardNoGeneratedVo);
		Iterator<CardNoGeneratedVo> iterator=list.iterator();
		while(iterator.hasNext()){
			CardNoGeneratedVo vo=iterator.next();
			if(vo.getCardpCode().equals(CardContants.CARD_P_CODE_JS)||vo.getCardpCode().equals(CardContants.CARD_P_CODE_WF)){
				iterator.remove();
			}
		}
		DwzPage<CardNoGeneratedVo> dPage=new DwzPage<>(cardNoGeneratedVo.getCurrentPage(), cardNoGeneratedVo.getNumPerPage(), list.size());
		dPage.setList(list);
		return dPage;
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Boolean generatorCitizenCardNo(String cardpCode,String prefix, Integer num) throws Exception {
		List<String> list=new ArrayList<>();
		//和银行生成卡号库不同
		CardNoGenerated c=cardNoGeneratedMapper.queryLastRecordByFlieNamePrefix("CN"+prefix);
		String fileSeq=null;//文件名序号
		String currentNo=null;
		int valid = 0;
		if (c == null) {
			currentNo="0000000";//市民卡号后7位
			fileSeq="0001";
		}else{
			currentNo=c.getEndSegmentNo();
			int a=c.getFileName().indexOf(".");
			fileSeq=CommonUtil.patchHexString(String.valueOf((Integer.valueOf(c.getFileName().substring(a-4, a))+1)), 4);
		}
		String dd=currentNo;//后7位
		for(int j=0;j<num;j++){
			String endNo = "";
			if (StringUtils.isNotEmpty(dd)) {
				endNo=dd;
			} else {
				throw new ApplicationException(ErrorCode.OBJECT_IS_NULL, "CitizenCardNo is null !!!");
			}
			logger.error("***************************上一条卡面号后7位*****：[{}]", dd);
			Integer newNo = Integer.parseInt(endNo) + 1;// 生成 后7位+1
			String gg = "";
			String s = "";
			int l = newNo.toString().length();
			if (endNo.indexOf("0") == 0 && l < 7) {
				int p = 7 - l;// 最后所需0的个数
				for (int i = 0; i < p; i++) {
					s += "0";
				}
				gg = s + newNo.toString();
			} else if (l == 7) {
				gg = newNo.toString();
			}

			valid = CardUtil.calcLuhn(prefix + gg);
			String newCardNo = prefix + valid + gg;// 组合卡面号
			if (CardUtil.verifyCardNo(newCardNo)) {
				list.add( newCardNo);
				dd=gg;
			}
			else {
				throw new ApplicationException(ErrorCode.DATA_ILLEGALITY, "卡面号不合法");
			}
		}
		String fileName="CN"+prefix+new SimpleDateFormat("yyMMdd").format(new Date())+fileSeq+".txt";
		String path=PathContants.FTP_PATH_CARDNOAUTONOMY;
		   	
		boolean b=false;
		logger.debug("卡号生成数量=="+list.size());		
		b=FileUtil.generatedCardNoText(list, fileName,path);
		
		if(b){
			if(list.size()==num){
				CardNoGenerated cardNoGenerated=new CardNoGenerated();
				cardNoGenerated.setCardpCode(cardpCode);
				cardNoGenerated.setCrtDate(new Date());
				cardNoGenerated.setEndSegmentNo(list.get(list.size()-1).substring(5));
				cardNoGenerated.setStartSegmentNo(list.get(0).substring(5));
				cardNoGenerated.setNum(num);
				cardNoGenerated.setFileName(fileName);
				cardNoGenerated.setUsedSegmentNo(0);
				cardNoGenerated.setIsUseUp("0");
				cardNoGenerated.setCardPhysicalType(prefix.substring(2,3));
				cardNoGeneratedMapper.insert(cardNoGenerated);
			}
		}
		return b;
		
	}

	

}
